package site.teamo.biu.net.common.coder;

import com.alibaba.fastjson2.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import site.teamo.biu.net.common.message.Message;

import java.util.List;

/**
 * @author haocongshun
 * @date 2023/02/10 10:50:55
 */
@Slf4j
public class MessageDecoder extends ByteToMessageDecoder {

    @Getter
    private final String name;

    public MessageDecoder(String name) {
        this.name = name;
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        long flag = in.readLong();
        if (flag != Message.flag) {
            ctx.fireChannelRead(in.resetReaderIndex().retain());
            return;
        }
        //读取数据大小
        int messageLength = in.readInt();
        //读取类型标识
        Message.Type type = Message.Type.codeOf(in.readInt());
        //读取实际数据
        byte[] messageBytes = new byte[messageLength];
        in.readBytes(messageBytes);

        //对数据进行类型转换
        Message message = JSON.parseObject(messageBytes, type.tClass);

        if (log.isDebugEnabled()) {
            log.info("{} 解码[{}]数据: {}Bytes", name, message.type(), messageBytes.length);
        }
        out.add(message);
    }

    public static void main(String[] args) {

    }
}
